import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @author chaird
 * @create 2023-05-20 12:54
 */
public class ForkJoinPoolDemo {
  public static void main(String[] args) throws Exception{

    ForkJoinPool forkJoinPool = new ForkJoinPool(4);
    ForkJoinTask<Integer> submit = forkJoinPool.submit(new RaskDemo(1, 25));
    System.out.println(submit.get());
  }

}

class RaskDemo extends RecursiveTask<Integer> {
    /**
     *  每个"小任务"最多只打印20个数
     */
    private static final int MAX = 20;

    private int start;
    private int end;

    public RaskDemo(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        //当end-start的值小于MAX时，开始打印
        if((end-start) < MAX) {
            int sum = 0;
            for(int i= start; i<end;i++) {
                sum += i;
            }
            return sum;
        }else {
            // 将大任务分解成两个小任务
            int middle = (start + end) / 2;
            RaskDemo left = new RaskDemo(start, middle);
            RaskDemo right = new RaskDemo(middle + 1, end);
            //并行执行两个 小任务
            left.fork();
            right.fork();
            //把两个小任务累加的结果合并起来
            Integer leftValue = left.join();
            Integer rightValue = right.join();
            return leftValue + rightValue;

        }

    }
}
